import java.util.*;

public class PushingAndPoppingSequencesOfAStack {
    public static void main(String[] args) {
        Solution solution = new Solution();

        // 测试用例
        int[] pushV1 = {1, 2, 3, 4, 5};
        int[] popV1 = {4, 5, 3, 2, 1};
        System.out.println("测试用例1: " + (solution.IsPopOrder(pushV1, popV1) ? "合法" : "不合法"));

        int[] pushV2 = {1, 2, 3, 4, 5};
        int[] popV2 = {4, 3, 5, 1, 2};
        System.out.println("测试用例2: " + (solution.IsPopOrder(pushV2, popV2) ? "合法" : "不合法"));
    }
}

// 原Solution类保持不变
class Solution {
    public boolean IsPopOrder (int[] pushV, int[] popV) {
        Stack<Integer> stack = new Stack<>();
        int i = 0;
        int j = 0;

        stack.push(pushV[i]);
        while (j < popV.length) {
            //判断栈是否与需求相同，否则再入栈
            if (!stack.isEmpty() && stack.peek() == popV[j]) {
                j++;
                stack.pop();
            } else {
                i++;
                if (i == pushV.length) {
                    return false;
                }
                stack.push(pushV[i]);
            }
        }

        return true;
    }
}